import Taro, {Component, Config} from "@tarojs/taro";
import {View, Image, Text, RichText} from "@tarojs/components";
import { AtTabs, AtTabsPane } from "taro-ui"
import {toJS} from 'mobx'
import {inject, observer} from '@tarojs/mobx'
import {IStoreProps} from '../../store/Stores'
import {getRuntime, htmlToText, pageSize, ServerHost, servicePhoneNumber} from '../../utils/common'

import '../business_school/index.less'
import '../business_school/detail.less'
import './course_detail.less'

import share from '../../assets/img/icon_46.png'
import tel from '../../assets/img/icon_47.png'
import time_long from '../../assets/img/icon_48.png'
import share_icon from "../../assets/img/share_arrow.png";
import close_icon from "../../assets/img/icon_close_bold.png";

// 建企商学院-详情
interface IHomeProps extends IStoreProps {}
@inject("stores")
@observer
class UserCourseDetail extends Component<IHomeProps> {
  constructor(props) {
    super(props)
  }

  state = {
    pageIndex:1,
    pageSize,
    items: [],
    totalCount:0,
    courseInformation:{},
    courseId: 1,
    currentNavId: 0,
    isCollection: false,
    isTips: false,
    tipsText: '',
    videoSrc: '',
    autoplay: false,
    currentPlayVideoId: -1,
    isShare: false
  }

  componentWillMount(): void {
    Taro.setNavigationBarTitle({ title:'我的课程' })
    let id = parseInt(this.$router.params.id)
    this.getJsApiParam()
    this.setState({
      courseId:id,
    }, () => {
      this.getCourseInformation()
      this.getCourseChapterInfo()
    })
  }

  componentDidMount(): void {
    const videoContext = Taro.createVideoContext('myVideo', this)
    this.setState({
      videoContext
    })
  }

  handelRouter(url: string = '/pages/index/index'): void {
    getRuntime().navigateTo(url)
  }

  config: Config = {
    navigationBarTitleText: '课程详情'
  }

  makePhone() {
    getRuntime().makePhoneCall(servicePhoneNumber)
  }

  changeNavId(id:number){
    this.setState({currentNavId: id})
  }

  scrollChangeNavId(e?){
    // console.log('滚动'+e.detail.current)
    this.setState({currentNavId: e.detail.current})
  }

  getCourseInformation() {
    let businessSchool = this.props.stores.BusinessSchool
    businessSchool.getCourseInformation({
      id: this.state.courseId,
      callback: res => {
        this.setState({
          courseInformation: res,
        }, () => {
          this.share()
        })
      }
    })
  }

  getCourseChapterInfo() {
    let businessSchool = this.props.stores.BusinessSchool
    let { courseId, pageIndex, pageSize } = this.state
    businessSchool.getCourseChapterInfo({
      formType: 2, // 用户中心
      courseId,
      pageIndex,
      pageSize,
      callback: res => {
        if(res.items){
          let videoSrc = res.items[0]['url']
          this.setState({ videoSrc })
        }
        if (pageIndex === 1) {
          this.setState({totalCount: toJS(res.totalCount), items: toJS(res.items)})
        }else {
          const { items } = this.state;
          items.push(...res.items || []);
          this.setState({totalCount: res.totalCount, items})
        }
      }
    })
  }

  getMore(): void {
    let {totalCount, pageSize, pageIndex} = this.state
    const {loading} = this.props.stores.homeStore;
    if (totalCount > pageIndex * pageSize && !loading) {
      this.setState({
        pageIndex: pageIndex + 1
      }, () => {
        this.getCourseChapterInfo()
      })
    }
  }

  // 设置显示的章节序号
  getChapterId(id:any) {
    if(id<10){
      id = '0'+id
    }
    return id
  }

  setVideoSrc(url: string, index: number) {
    if(!url) { getRuntime().showToast('视频不存在或已下架~'); return }
    let videoContext = document.getElementById("taroVideo");
    this.setState({
      videoSrc: url,
      autoplay: true,
      currentPlayVideoId: -1
    }, () => {
      if(videoContext){
        videoContext.play()
      }
      /*if(videoplay){
        document.addEventListener("WeixinJSBridgeReady",function() {
          videoplay.play();
        }, false);
      }*/
    })
    /*var isIphone = navigator.userAgent.indexOf('iPhone') >= 0;
    console.log(navigator.userAgent)
    if (isIphone) {
      window.location.href=url
    }else {
      this.setState({
        videoSrc: url,
        autoPlay: true,
        currentPlayVideoId: index
      })
    }*/
  }

  // 购买课程
  buyCourse(courseChapterId:any = null ) {
    if(!getRuntime().getToken()) { getRuntime().navigateTo('/pages/login/login'); return }
    getRuntime().showModal('您确定要购买此课程吗?','',() => {
      let { courseId } = this.state
      let { BusinessSchool } = this.props.stores
      if(!courseId) { getRuntime().showToast('参数错误~'); return }
      if(courseChapterId==='all') { courseChapterId=null }

      BusinessSchool.buyCourse({
        form: {
          courseInfoId: courseId,
          courseChapterId
        },
        callback: res => {
          getRuntime().wxPay(res, () => {
           getRuntime().showToast('恭喜您, 购买课程成功~')
            this.getCourseChapterInfo()
          })
        }
      })
    })
  }

  // 配置微信分享
  getJsApiParam = () => {
    let currentUrl = window.location.href
    let apiUrl = `${ServerHost}/api/Account/getWxJsApiParams?curUrl=${currentUrl}`
    Taro.showLoading({title: '加载中...'})
    fetch(apiUrl, {
      method: 'GET',
      mode: "cors",
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
      },
      credentials: 'same-origin'
    })
      .then(response => {
        Taro.hideLoading()
        return response.json()
      })
      .then(response => {
        let appId = response.appId
        let timestamp = response.timestamp
        let nonceStr = response.nonceStr
        let signature = response.signature
        this.setState({ wxConfig: response })
        wx.config({
          debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
          appId: appId, // 必填，公众号的唯一标识
          timestamp: timestamp, // 必填，生成签名的时间戳
          nonceStr: nonceStr, // 必填，生成签名的随机串
          signature: signature,// 必填，签名
          // jsApiList: ['updateAppMessageShareData','onMenuShareAppMessage'], // 必填，需要使用的JS接口列表
          jsApiList: 'updateAppMessageShareData,onMenuShareTimeline,onMenuShareAppMessage,onMenuShareQQ,onMenuShareWeibo'.split(',')
        });
      })
      .catch(error => {
        console.log(error)
      })
  }

  share() {
    // if(!getRuntime().getToken()) { getRuntime().navigateTo('/pages/login/login'); return }
    let item = this.state.courseInformation
    let url1 = ServerHost+'/m/#/pages/business_school/detail?id='+item.id
    let title = item.courseName
    let desc = htmlToText(item.courseContent)
    let imgUrl = item.courseLogoImg
    var shareData = {
      title,
      desc,
      imgUrl,
      otherImgUrl: '',
      url: window.location.href,
      link: window.location.href
    };
    wx.ready(function () {   //需在用户可能点击分享按钮前就先调用
      wx.onMenuShareTimeline(shareData);
      wx.updateAppMessageShareData(shareData);
      wx.onMenuShareQQ(shareData);
      wx.onMenuShareWeibo(shareData);
    });
    // WxShare(url,item.logo,item.title,partOf(item.content, 30))
  }

  btnShare() {
    this.setState({ isShare: true })
  }

  onClose() {
    this.setState({ isShare: false })
  }

  componentDidHide(): void {
    this.setState({ isShare: false })
  }

  endedVideo() {
    this.setState({ currentPlayVideoId: -1 })
  }

  pauseVideo() {
    this.setState({ currentPlayVideoId: -1 })
  }

  render() {
    let { courseInformation, items,totalCount, currentNavId,videoSrc, autoplay,currentPlayVideoId,isShare} = this.state
    let teacherInfo = courseInformation.teacherInfo
    const tabList = [{ title: '目录' }, { title: '课程详情' }, { title: '机构简介' }]
    return (
      <View className='college-course-detail'>
        {/*<Video className='video'
               id='taroVideo'
               src={videoSrc}
               controls={true}
               autoplay={autoplay}
               poster={courseInformation.courseLogoImg}
               initialTime='0'
               loop={false}
               preload={true}
               onEnded={this.endedVideo.bind(this)}
               onPause={this.pauseVideo.bind(this)}
               playsinline={true}           //react项目中警告，所以把true用{}包起来了
               webkit-playsinline={true}     //兼容ios
               x5-playsinline={true}        //兼容安卓
        />*/}
        <View className='video-wrap'>
          {videoSrc&&
          <video
            style={{width: '100%', objectFit: 'contain'}}
            controls
            autoPlay={autoplay}
            preload="auto"
            poster={courseInformation.courseLogoImg}
            x-webkit-airplay={true}
            webkit-playsinline={true}
            playsinline={true}
            x5-video-player-type='h5'
            x5-video-player-fullscreen={true}
            src={videoSrc}
            >
            </video>
          }
          {!videoSrc&&
          <Image className='video' src={courseInformation.courseLogoImg} />
          }
          <View className='line'>
            <View className='title'>{courseInformation.courseName}</View>
            <View className='btn-share' onClick={this.btnShare.bind(this)}>
              <Image className={'share-icon'} src={share} />
              <Text className='share-name'>分享</Text>
            </View>
          </View>
          <View className='line'>
            <View className='num'>{courseInformation.studyCount}人学过</View>
            <View className='all'>共 <Text className={'count'}>{items.length}</Text>个课程</View>
          </View>
        </View>

        <View className='interval' />

        <AtTabs current={currentNavId} tabList={tabList} onClick={this.changeNavId.bind(this)} className='course-detail'>
          <AtTabsPane current={currentNavId} index={0} >
            <View className='item catalog'>
              <View className='list-09'>
                {items.length>0&&
                items.map((item,index) => {
                  let tpl = null
                  /*if(item.isFree){
                    tpl =
                      <View className='list-09-item'>
                        <View className='line'>
                          <View className='top'>
                            <View className='index'>{this.getChapterId(index+1)}</View>
                            <View className='title'>{item.chaptersTitle}</View>
                            <View className='try' onClick={this.setVideoSrc.bind(this,item.url, index)}>试看</View>
                          </View>
                          <View className='free'>免费</View>
                        </View>
                        <View className='line line2'>
                          <Image src={time_long} className={'time-icon'} />
                          <View className='time-long'>56;56</View>
                        </View>
                      </View>
                  }*/
                   if(item.isFree || item.isBuy) {
                    tpl =
                    <View className='list-09-item'>
                      <View className='line'>
                        <View className='top'>
                          <View className='index'>{this.getChapterId(index+1)}</View>
                          <View className='title'>{item.chaptersTitle}</View>
                        </View>
                        {currentPlayVideoId===index&&<View className='free once-play' onClick={this.setVideoSrc.bind(this,item.url,index)}>播放中...</View>}
                        {currentPlayVideoId!==index&&<View className='free' onClick={this.setVideoSrc.bind(this,item.url,index)}>立即播放</View>}
                      </View>
                      <View className='line line2'>
                        <Image src={time_long} className={'time-icon'} />
                        <View className='time-long'>56:35</View>
                      </View>
                    </View>
                  }
                  else{
                    tpl =
                    <View className='list-09-item list-09-item-disable' onClick={this.buyCourse.bind(this,item.id)}>
                      <View className='line'>
                        <View className='top'>
                          <View className='index'>{this.getChapterId(index+1)}</View>
                          <View className='title'>{item.chaptersTitle}</View>
                        </View>
                        <View className='free'><Text className='list-small'>￥</Text>{item.price}</View>
                      </View>
                      <View className='line line2'>
                        <Image src={time_long} className={'time-icon'} />
                        <View className='time-long'>56:35</View>
                      </View>
                    </View>
                  }
                  return tpl
                })
                }
                {items.length<totalCount&&  <View className='view-more color-light' onClick={this.getMore.bind(this)}>查看更多</View>}
              </View>
              <View className='interval' />
              <View className='teacher-wrap'>
                {teacherInfo&&
                <View className='column-title'>
                   <Text className='column-name'>讲师介绍</Text>
                </View>
                }
                {teacherInfo&&
                teacherInfo.map(item => {
                  return(
                    <View className='list-10-item'>
                      <Image src={item.teacherLogo} className='teacher-pic' />
                      <View className='info'>
                        <View className='title'>{item.teacherName }</View>
                        <View className='desc'>{item.teacherIntroduce}</View>
                      </View>
                    </View>
                  )
                })
                }
              </View>

            </View>
          </AtTabsPane>
          <AtTabsPane current={currentNavId} index={1}>
            <View className='item detail rich-text'>
              <RichText nodes={courseInformation.courseContent} />
            </View>
          </AtTabsPane>
          <AtTabsPane current={currentNavId} index={2}>
            <View className='item desc'>
              <View className='company'>
                <Image className='logo' src={courseInformation.mechanismLogo}/>
                <View className='info'>
                  <View className='title'>{courseInformation.mechanism}</View>
                  <View className='desc-info'>{courseInformation.introduce}</View>
                </View>
              </View>

              <View className='column-title content-30'>
                <Text className='column-name'>机构简介</Text>
              </View>

              <View className='item-lawyer-desc'>
                <RichText nodes={courseInformation.mechanismContent} />
              </View>

              <View className='column-title content-30'>
                <Text className='column-name'>联系方式</Text>
              </View>

              <View className='item-lawyer'>
                <View className={'line'}>
                  <Text className='title'>招生电话：</Text>
                  <Text className='name'>{courseInformation.phoneNumber}</Text>
                </View>
                <View className={'line'}>
                  <Text className='title'>电子邮箱：</Text>
                  <Text className='name'>{courseInformation.emailAddress}</Text>
                </View>
                <View className={'line'}>
                  <Text className='title'>学校网站：</Text>
                  <View className='name'>
                    <Text>{courseInformation.webAddress}</Text>
                  </View>
                </View>
                <View className={'line'}>
                  <Text className='title'>机构地址：</Text>
                  <Text className='name'>{courseInformation.address}</Text>
                </View>
              </View>
            </View>
          </AtTabsPane>
        </AtTabs>

        <View className='footer-block' />
        <View className='college-footer'>
          <View className='nav' />
          <View className='nav' onClick={this.makePhone}>
            <Image className='nav-icon nav-icon2' src={tel} />
            <View>电话咨询</View>
          </View>
          <View className='nav nav-active' onClick={this.buyCourse.bind(this,'all')}>
            <View>购买全部课程</View>
          </View>
        </View>

        <View className={isShare?'share-arrow share-arrow-active':'share-arrow'}>
          <Image className='share-arrow-icon' src={share_icon} />
          <View className='con'>
            <View>请点击右上角</View>
            <View>通过【发送给朋友】</View>
            <View>分享给好友</View>
          </View>
          <Image className='close-icon' onClick={this.onClose.bind(this)} src={close_icon} />
        </View>
      </View>
    )
  }
}
export default UserCourseDetail
